package com.itheima.dubbo.api;

import com.tanhua.domain.mogo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    //查询两个用户之间的缘分值
    @Override
    public Long findRecommendScore(Long targetUserId, Long toUserId) {
        Criteria criteria=Criteria.where("userId").is(targetUserId).and("toUserId").is(toUserId);
        RecommendUser recommendUser = mongoTemplate.findOne(new Query(criteria), RecommendUser.class);
        if (recommendUser!=null){
            return recommendUser.getScore().longValue();
        }

        return 95L;
    }

    @Override
    public PageResult<RecommendUser> recommendUserList(Long userId, int page, int pagesize) {
        //where touserId=当前用户
        Criteria criteria=Criteria.where("toUserId").is(userId);
        //order by score  desc 分页查询
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("score")))
                .with(PageRequest.of(page-1,pagesize));

        //分页查询列表
        List<RecommendUser> userList = mongoTemplate.find(query, RecommendUser.class);
        //查询数量
        long count = mongoTemplate.count(query, RecommendUser.class);
        //计算页数
        int pages= (int) Math.ceil(count*1.0/pagesize);
        //封装结果
        return  new PageResult<>((int) count,pagesize,pages,page,userList);

    }

    @Override
    public RecommendUser findMaxScoreUser(Long userId) {
        //where toUserId =用户Id
        Criteria criteria = Criteria.where("toUserId").is(userId);

        //按照score值降序排列 查询第一条
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))
                .limit(1);
        return mongoTemplate.findOne(query,RecommendUser.class);
    }
}
